<template>
  <div class="admin-management">
    <el-card>
      <div slot="header">
        <span>管理员管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">添加管理员</el-button>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索用户名、姓名或邮箱"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.role" placeholder="选择角色" clearable>
              <el-option label="超级管理员" value="super_admin" />
              <el-option label="普通管理员" value="admin" />
              <el-option label="审核员" value="reviewer" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 管理员列表 -->
      <el-table
        :data="adminList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="120">
          <template slot-scope="scope">
            {{ scope.row.name || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="120">
          <template slot-scope="scope">
            <el-tag :type="getRoleType(scope.row.role)" size="small">
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.lastLoginAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="primary" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.role === 'super_admin'"
            >
              编辑
            </el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
              :disabled="scope.row.role === 'super_admin'"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.role === 'super_admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 管理员详情/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        :model="adminForm"
        :rules="adminRules"
        ref="adminForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="adminForm.username" 
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="adminForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="adminForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="普通管理员" value="admin" />
            <el-option label="审核员" value="reviewer" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="adminForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input 
            v-model="adminForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="adminForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 管理员详情对话框 -->
    <el-dialog
      title="管理员详情"
      :visible.sync="detailDialogVisible"
      width="500px"
    >
      <div v-if="currentAdmin" class="admin-detail">
        <div class="detail-item">
          <label>ID:</label>
          <p>{{ currentAdmin.id }}</p>
        </div>
        <div class="detail-item">
          <label>用户名:</label>
          <p>{{ currentAdmin.username }}</p>
        </div>
        <div class="detail-item">
          <label>姓名:</label>
          <p>{{ currentAdmin.name || '未设置' }}</p>
        </div>
        <div class="detail-item">
          <label>邮箱:</label>
          <p>{{ currentAdmin.email }}</p>
        </div>
        <div class="detail-item">
          <label>角色:</label>
          <p>
            <el-tag :type="getRoleType(currentAdmin.role)" size="small">
              {{ getRoleName(currentAdmin.role) }}
            </el-tag>
          </p>
        </div>
        <div class="detail-item">
          <label>状态:</label>
          <p>
            <el-tag :type="getStatusType(currentAdmin.status)" size="small">
              {{ getStatusName(currentAdmin.status) }}
            </el-tag>
          </p>
        </div>
        <div class="detail-item">
          <label>最后登录:</label>
          <p>{{ formatDate(currentAdmin.lastLoginAt) }}</p>
        </div>
        <div class="detail-item">
          <label>创建时间:</label>
          <p>{{ formatDate(currentAdmin.createdAt) }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AdminManagement",
  data() {
    return {
      loading: false,
      submitLoading: false,
      adminList: [],
      searchForm: {
        keyword: "",
        role: "",
        status: ""
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      dialogTitle: "",
      isEdit: false,
      currentAdmin: null,
      adminForm: {
        id: null,
        username: "",
        name: "",
        email: "",
        role: "admin",
        status: "active",
        password: "",
        confirmPassword: ""
      },
      adminRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
        ],
        role: [
          { required: true, message: "请选择角色", trigger: "change" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度不能少于6位", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" }
        ]
      }
    }
  },
  async created() {
    await this.loadAdminList()
  },
  methods: {
    async loadAdminList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await this.$http.get("/admin/admins", { params })
        if (response.data.code === 200) {
          this.adminList = response.data.data.list
          this.pagination.total = response.data.data.total
        }
      } catch (error) {
        console.error("加载管理员列表失败:", error)
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },

    loadMockData() {
      this.adminList = [
        {
          id: 1,
          username: "admin",
          name: "系统管理员",
          email: "admin@example.com",
          role: "super_admin",
          status: "active",
          lastLoginAt: "2025-09-20T10:30:00",
          createdAt: "2025-09-01T00:00:00"
        },
        {
          id: 2,
          username: "reviewer1",
          name: "审核员1",
          email: "reviewer1@example.com",
          role: "reviewer",
          status: "active",
          lastLoginAt: "2025-09-19T15:20:00",
          createdAt: "2025-09-05T00:00:00"
        },
        {
          id: 3,
          username: "admin1",
          name: "普通管理员",
          email: "admin1@example.com",
          role: "admin",
          status: "disabled",
          lastLoginAt: "2025-09-18T09:15:00",
          createdAt: "2025-09-10T00:00:00"
        }
      ]
      this.pagination.total = 3
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadAdminList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        role: "",
        status: ""
      }
      this.pagination.currentPage = 1
      this.loadAdminList()
    },

    handleAdd() {
      this.dialogTitle = "添加管理员"
      this.isEdit = false
      this.adminForm = {
        id: null,
        username: "",
        name: "",
        email: "",
        role: "admin",
        status: "active",
        password: "",
        confirmPassword: ""
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = "编辑管理员"
      this.isEdit = true
      this.adminForm = {
        id: row.id,
        username: row.username,
        name: row.name || "",
        email: row.email,
        role: row.role,
        status: row.status,
        password: "",
        confirmPassword: ""
      }
      this.dialogVisible = true
    },

    handleView(row) {
      this.currentAdmin = row
      this.detailDialogVisible = true
    },

    async handleToggleStatus(row) {
      const newStatus = row.status === 'active' ? 'disabled' : 'active'
      const action = newStatus === 'active' ? '启用' : '禁用'
      
      try {
        await this.$confirm(`确定要${action}该管理员吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.put(`/admin/admins/${row.id}/status`, {
          status: newStatus
        })
        
        if (response.data.code === 200) {
          this.$message.success(`${action}成功`)
          this.loadAdminList()
        } else {
          this.$message.error(response.data.message || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${action}管理员失败:`, error)
          this.$message.error(`${action}失败`)
        }
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该管理员吗？删除后不可恢复！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.delete(`/admin/admins/${row.id}`)
        
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.loadAdminList()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除管理员失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSubmit() {
      try {
        await this.$refs.adminForm.validate()
        this.submitLoading = true

        const url = this.isEdit ? `/admin/admins/${this.adminForm.id}` : '/admin/admins'
        const method = this.isEdit ? 'put' : 'post'
        
        const formData = { ...this.adminForm }
        if (this.isEdit) {
          delete formData.password
          delete formData.confirmPassword
        } else {
          delete formData.confirmPassword
        }
        
        const response = await this.$http[method](url, formData)
        
        if (response.data.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '添加成功')
          this.dialogVisible = false
          this.loadAdminList()
        } else {
          this.$message.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败')
      } finally {
        this.submitLoading = false
      }
    },

    handleDialogClose() {
      this.$refs.adminForm.resetFields()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadAdminList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadAdminList()
    },

    validateConfirmPassword(rule, value, callback) {
      if (value !== this.adminForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    },

    getRoleType(role) {
      const roleMap = {
        super_admin: "danger",
        admin: "primary",
        reviewer: "warning"
      }
      return roleMap[role] || "info"
    },

    getRoleName(role) {
      const roleMap = {
        super_admin: "超级管理员",
        admin: "普通管理员",
        reviewer: "审核员"
      }
      return roleMap[role] || "未知"
    },

    getStatusType(status) {
      const statusMap = {
        active: "success",
        disabled: "danger"
      }
      return statusMap[status] || "info"
    },

    getStatusName(status) {
      const statusMap = {
        active: "正常",
        disabled: "禁用"
      }
      return statusMap[status] || "未知"
    },

    formatDate(date) {
      if (!date) return '未登录'
      return new Date(date).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.admin-management {
  padding: 0;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.admin-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.detail-item p {
  margin: 5px 0;
  line-height: 1.6;
}
</style>
